/**
 * Copyright (c) 2014,Egret-Labs.org
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Egret-Labs.org nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

class Main extends egret.DisplayObjectContainer {

    /**
     * 加载进度界面
     * loading process interface
     */
    private loadingView:LoadingUI;
    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }
    private onAddToStage(event: egret.Event) {
        egret.Injector.mapClass("egret.gui.IAssetAdapter", AssetAdapter);
        egret.gui.Theme.load("resource/theme.thm");
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/resource.json", "resource/");
    }
    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * Loading of configuration file is complete, start to pre-load the preload resource group
     */
    private onConfigComplete(event: RES.ResourceEvent): void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.loadGroup("loading");
    }
    /**
     * preload资源组加载完成
     * preload resource group is loaded
     */
    private onResourceLoadComplete(event: RES.ResourceEvent): void {
        if (event.groupName == "loading") {
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            this.guiLayer=new egret.gui.UIStage();
            this.loadingView = new LoadingUI();
            this.guiLayer.addElement(this.loadingView);
            this.addChild(this.guiLayer);

            RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            RES.loadGroup("preload");
        }else if(event.groupName == "preload"){
            this.guiLayer.removeElement(this.loadingView);
            this.createScene();
        }
    }
    /**
    * 资源组加载出错
     * Resource group loading failed
    */
    private onResourceLoadError(event: RES.ResourceEvent): void {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //ignore loading failed projects
        this.onResourceLoadComplete(event);
    }
    /**
     * preload资源组加载进度
     * loading process of preload resource
     */
    private onResourceProgress(event: RES.ResourceEvent): void {
        if (event.groupName == "preload") {
            this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
        }
    }
    private gameLayer: egret.DisplayObjectContainer;
    private guiLayer: egret.gui.UIStage;
    private startPop:StartPop;
    private mainStage:MainStage;
    private endPop:EndPop;
    private gameCtrl:GameController;
    private countdown:egret.Timer;
    private t:number;
    private s:number;
    private MAX_TIME:number=10;
    /**
     * 创建场景界面
     * Create scene interface
     */
    private createScene(): void {
        var that=this;
        var bodyConfig:BodyConfig = new BodyConfig();
        bodyConfig.appId = "wx2e1cc1c7a9cf5382";
        bodyConfig.nonceStr="fasdftryutyjgh";
        bodyConfig.timestamp=1433830024;//new Date().getTime();
        bodyConfig.signature = "0d452ed83189ff7ce3005191fc11f538d5f22948";
        bodyConfig.debug = true;
        /// ... 其他的配置属性赋值
        /// 通过config接口注入权限验证配置
        var bodyMenuShareTimeline:BodyMenuShareTimeline=new BodyMenuShareTimeline();
        bodyMenuShareTimeline.title="测试分享";
        bodyMenuShareTimeline.link="http://m.fang.com/";
        bodyMenuShareTimeline.imgUrl="";
        bodyMenuShareTimeline.success=that.shareBack;
        if(wx) {
            wx.config(bodyConfig);
            wx.ready(function () {
                that.init();
                wx.onMenuShareTimeline(bodyMenuShareTimeline);
            });
        }
    }
    private init():void{
        this.t=this.MAX_TIME;
        this.s=0;
        if(!this.countdown){
            this.countdown=new egret.Timer(1000);
            this.gameLayer=new egret.DisplayObjectContainer();
            this.addChild(this.gameLayer);
            this.startPop=new StartPop();
            this.guiLayer.addElement(this.startPop);
            this.mainStage=new MainStage();
            this.guiLayer.addElement(this.mainStage);
            this.endPop=new EndPop();
            this.guiLayer.addElement(this.endPop);
            this.gameCtrl=new GameController();
            this.gameLayer.addChild(this.gameCtrl);
            this.countdown.addEventListener(egret.TimerEvent.TIMER,this.TimeRun,this);
            this.guiLayer.addEventListener(GuiEvent.START_GAME,this.onStartGame,this);
            this.guiLayer.addEventListener(GuiEvent.AGAIN_GAME,this.onAgainGame,this);
            this.gameLayer.addEventListener(GuiEvent.CLICK_HOUSE,this.onClickHouse,this);
        }else{
            this.swapChildren(this.gameLayer,this.guiLayer);
        }
        this.mainStage.setScore(this.s);
        this.mainStage.showTime(this.t,this.MAX_TIME);
        this.gameCtrl.clear();
        this.gameCtrl.visible=false;
        this.startPop.visible=true;
        this.mainStage.visible=false;
        this.endPop.visible=false;
    }
    private TimeRun(e:egret.TimerEvent):void{
        this.t--;
        this.mainStage.showTime(this.t,this.MAX_TIME);
        if(this.t<=0){
            this.gameOver();
        }
    }
    private onStartGame(e:GuiEvent):void{
        this.startPop.visible=false;
        this.mainStage.visible=true;
        this.gameCtrl.gameStart();
        this.countdown.start();
    }
    private onAgainGame(e:GuiEvent):void{
        this.init();
    }
    private onClickHouse(e:GuiEvent):void{
        this.s++;
        this.mainStage.setScore(this.s);
    }
    private gameOver():void{
        this.countdown.reset();
        this.countdown.stop();
        this.gameCtrl.gameOver();
        this.swapChildren(this.gameLayer,this.guiLayer);
        this.endPop.setScore(this.s);
        this.endPop.visible=true;
    }
    private shareBack():void{
        alert("分享成功");
    }
}


